from dateutil.relativedelta import relativedelta
from fastapi import APIRouter, Query, UploadFile, BackgroundTasks
from fastapi.responses import JSONResponse
from tortoise.expressions import Q

from app.controllers.checkins.checkin import checkin_controller
from datetime import time, datetime

from app.controllers.marketing.integral import integral_controller
from app.controllers.marketing.integral_rule import integral_rule_controller
from app.schemas.base import Success, SuccessExtra, Fail
from app.core.dependency import DependCustomerAuth
from app.core.ctx import CTX_USER_ID
from app.schemas.checkin import CheckinCreate

checkin_router = APIRouter()
model_name = "签到"


@checkin_router.get("/list", summary=f"查看{model_name}列表", dependencies=[DependCustomerAuth])
async def do_list(
        page: int = Query(1, description="页码"),
        page_size: int = Query(400, description="每页数量"),
        start_time: datetime = Query(None, description=f"时间"),
        end_time: datetime = Query(None, description=f"时间"),
):
    q = Q()
    user_id = CTX_USER_ID.get()
    q &= Q(user_id=user_id)
    if start_time:
        q &= Q(checkin_time__gte=start_time)
    if end_time:
        new_end_time = (end_time + relativedelta(days=1)).strftime("%Y-%m-%d")
        q &= Q(checkin_time__lt=new_end_time)
    total, data = await checkin_controller.do_list(page=page, page_size=page_size, search=q)
    print(data)
    time_diff = end_time - start_time
    days_diff = int(time_diff.days)+1
    date = []
    for day in range(days_diff):
        new_date = start_time + relativedelta(days=day)
        new_date_str = new_date.strftime("%Y-%m-%d")
        res = {'date': new_date_str, 'is_checkin': 0}

        for item in data:
            dt = datetime.strptime(item['checkin_time'], "%Y-%m-%d %H:%M:%S")
            date_str = dt.strftime("%Y-%m-%d")
            if date_str == res['date']:
                res['is_checkin'] = 1

        date.append(res)
    price = await integral_controller.do_user_info(user_id=user_id)
    role_value = await integral_rule_controller.do_detail(data_id=3)
    checkin_data = {
        'date': date,
        'price': int(price),
        'role_value': role_value['role'],
        'total': int(total)
    }
    return Success(data=checkin_data)


@checkin_router.get("/create", summary=f"{model_name}", dependencies=[DependCustomerAuth])
async def do_create(
    space_id: int = Query(0, description="门店id"),
):
    user_id = CTX_USER_ID.get()
    now = datetime.now()
    # 格式化输出
    local_time = now.strftime("%Y-%m-%d %H:%M:%S")
    obj_in = CheckinCreate(
        user_id=user_id,
        checkin_time=local_time
    )

    ret = await checkin_controller.do_create(obj_in=obj_in,space_id=space_id)
    if ret:
        return Success(msg="签到成功")
    else:
        return JSONResponse(content={"code": 400, "msg": "已签到"}, status_code=200)
